package tw.com.diary.core;

import java.util.List;
import java.util.UUID;

import tw.com.diary.ae.com.DirayBussinessException;
import tw.com.diary.api.com.Contract;
import tw.com.diary.api.domain.CalendarDTO;
import tw.com.diary.api.service.CalendarService;
import tw.com.diary.dao.X0001DAO;
import tw.com.diary.db.domain.X0001;
import tw.com.diary.db.util.DBHelp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

public class CalendarServiceImpl implements CalendarService {

	@Override
	public void writeBook(CalendarDTO dto, Context context)
			throws DirayBussinessException {
		DBHelp dbHelp = DBHelp.intance(context);

		SQLiteDatabase conn = dbHelp.getWritableDatabase();

		try {
			conn.beginTransaction();

			if (dto.isInsert()) {

				ContentValues values = new ContentValues();

				values.put(X0001DAO.CONTENT, dto.getContent());
				values.put(X0001DAO.UUID, dto.getUuid());
				values.put(X0001DAO.YYYYMMDD, dto.getYyyymmdd());
				values.put(X0001DAO.WEATHER, dto.getWeather());

				conn.insert("X0001", null, values);
			} else {

				ContentValues values = new ContentValues();

				values.put(X0001DAO.CONTENT, dto.getContent());
				values.put(X0001DAO.UUID, dto.getUuid());
				values.put(X0001DAO.YYYYMMDD, dto.getYyyymmdd());
				values.put(X0001DAO.WEATHER, dto.getWeather());
				

				conn.update("X0001", values, "uuid=?",
						new String[] { dto.getUuid() });
			}

			conn.setTransactionSuccessful();
		} catch (Exception e) {

		} finally {
			conn.endTransaction();
			conn.close();
		}

	}

	@Override
	public void inti(CalendarDTO dto, Context context)
			throws DirayBussinessException {
		final String yyyymmdd = dto.getYyyymmdd();

		DBHelp dbHelp =  DBHelp.intance(context);

		SQLiteDatabase conn = dbHelp.getReadableDatabase();
		X0001DAO dao = new X0001DAO(conn);

		final List<X0001> results = dao.selectYyymmdd(dto.getYyyymmdd());

		if (!results.isEmpty()) {
			dto.setInsert(false);
		} else {
			dto.setInsert(true);
		}

		if (dto.isInsert()) {
			dto.setUuid(UUID.randomUUID().toString());
			dto.setContent(Contract.BLANK);
		} else {

			final X0001 x0001 = results.get(0);

			dto.setUuid(x0001.getUuid());
			dto.setYyyymmdd(x0001.getYyyymmdd());
			dto.setContent(x0001.getContent());
			dto.setOldContent(x0001.getContent());
		}
		conn.close();

	}
}
